<template>
  <view class="exchange-container">
    <!-- 顶部标题 -->
    <view class="header">
      <!-- <text class="title">兑换</text> -->
    </view>

    <!-- 余额信息 -->
    <view class="balance-grid">
      <view class="grid-item">
        <text class="label">当前余额</text>
        <text class="value">{{ userInfo.balance || "0.00" }}</text>
        <text class="unit">SHUC积分</text>
      </view>
      <view class="grid-item">
        <text class="label">卡片数量</text>
        <text class="value">{{ userInfo.cardCount || "0" }}</text>
        <text class="unit">张</text>
      </view>
    </view>

    <!-- 兑换信息 -->
    <view class="exchange-info">
      <text class="section-title">兑换信息</text>
      <view class="info-row">
        <text class="label">今日价格</text>
        <text class="value">{{ todayPrice || "--" }} SHUC积分/张</text>
      </view>
      <view class="info-row">
        <text class="label">兑换数量</text>
        <view class="input-wrapper">
          <input
            type="number"
            v-model="exchangeCode"
            :placeholder="`不超过${userInfo.cardCount}张`"
            @input="onInputCode"
          />
        </view>
      </view>
    </view>

    <!-- 说明信息 -->
    <view class="notice-section">
      <text class="section-title">兑换说明</text>
      <view class="notice-content">
        <text class="notice-item"
          >1. 兑换只限于将卡片根据当时价格兑换成SHUC积分</text
        >
        <text class="notice-item">2. 兑换不收取任何手续费</text>
      </view>
    </view>

    <!-- 兑换按钮 -->
    <button
      class="submit-btn"
      @click="handleExchange"
      :disabled="!exchangeCode || isExchanging"
    >
      立即兑换
    </button>
  </view>
</template>

<script>
import authApi from "@/asstes/api/auth";
import goodsApi from "@/asstes/api/goods";
import userApi from "@/asstes/api/user";

export default {
  name: "ExchangePage",

  data() {
    return {
      userInfo: {
        balance: "0.00",
        cardCount: 0,
        status: 0,
      },
      todayPrice: "--",
      exchangeCode: "",
      isExchanging: false,
      socket: null,
      messages: [],
      heartbeatTimer: null
    };
  },
  onLoad() {
    this.connectWebSocket();
      this.getCurrentUserInfo();
    this.getShopPrice();
      
  },
      onUnload() {
    if (this.socket) {
      this.socket.close();
    }
    if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
  },

  methods: {
       connectWebSocket() {
      // 定时发送心跳
      this.heartbeatTimer = setInterval(() => {
        if (this.socket.readyState === this.socket.OPEN) {
          this.socket.send({
            data: 'ping'
          });
        }
      }, 30000);
      // 动态判断环境（开发环境可能需代理）
      const isDev = process.env.NODE_ENV === 'development';
      const wsUrl = isDev ? 'ws://www.pc.sanhuijucai.com/ws/message' : 'wss://your-domain.com/ws/message';
      
      this.socket = uni.connectSocket({
        url: wsUrl,
        success: () => {
          console.log('WebSocket 连接初始化');
        }
      });

      // 监听事件
      this.socket.onOpen(() => {
        console.log('WebSocket 连接成功');
        // 发送认证信息（若需要）
        this.socket.send({
          data: JSON.stringify({ type: 'auth', token: '用户token' })
        });
      });

      this.socket.onMessage((res) => {
        if (res !== "pong") { 
        const message = JSON.parse(res.data);
        console.log("接收到消息：", message)
        if (message.price) { 
          if (this.todayPrice != message.price) { 
            this.todayPrice = message.price;
            uni.showModal({
              title: "价格已变动",
              content: `确定要继续兑换吗？价格：${message.price}积分`,
              success: (res) => {
                console.log("res", res);
                if (res.confirm) {
                  console.log("用户点击确定兑换卡片");
                } else { 
                  uni.showToast({
                    title: "您已取消兑换",
                    type: "none"
                  })
                }
              },
            });
            return
          }
        }
        if (message.freezeStatus) { 
            console.log("freezeStatus",message.freezeStatus)
            uni.showModal({
              title: "账户异常通知",
              content: `该账户已被冻结，无法进行交易`,
              success: (res) => {
                console.log("res", res);
                if (res.confirm) {  
                  console.log("用户点击确定");
                }
              },
            });
            return
          }
        }
      });

      this.socket.onError((err) => {
        console.error('WebSocket 错误:', err);
        // 断线重连
        setTimeout(() => this.connectWebSocket(), 3000);
      });

      this.socket.onClose(() => {
        console.log('WebSocket 连接关闭');
      });
    },
    async getShopPrice() {
      try {
        this.loading = true;
        const res = await goodsApi.list();
        if (res.code === 200 && res.rows.length > 0) {
          this.todayPrice = res.rows[0].price;
        }
      } catch (error) {
        console.error("获取当天价格失败:", error);
        uni.showToast({
          title: "获取当天价格失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },
    async getCurrentUserInfo() {
      try {
        const userInfo = JSON.parse(localStorage.getItem("userInfo"));
        this.userInfo = userInfo;
        console.log("用户信息:", userInfo);
        const data = {
          userId: 0,
          sysUserId: userInfo.userId,
        };
        const response = await authApi.getUserInfo(data);
        console.log("用户信息:", response);
        if (response.code === 200) {
          if (response.user) {
            this.userInfo = response.user;
          }
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        uni.showToast({
          title: "获取用户信息失败",
          icon: "none",
        });
      }
    },
    onInputCode(e) {
      const value = e.detail.value;
      // 验证输入是否超过卡片数量
      if (Number(value) > this.userInfo.cardCount) {
        uni.showToast({
          title: "兑换数量不能超过持有数量",
          icon: "none",
        });
        return;
      }
      this.exchangeCode = value;
    },

    async handleExchange() {
      if (!this.exchangeCode) {
        uni.showToast({
          title: "请输入兑换数量",
          icon: "none",
        });
        return;
      }

      this.isExchanging = true;

      try {
        // TODO: 调用兑换接口

        const res = await userApi.exchange({
          cardCount: this.exchangeCode,
          userId: this.userInfo.userId,
        });

        console.log("兑换结果：", res);

        if (res.code === 200) {
          uni.showToast({
            title: "兑换成功",
            icon: "success",
          });
          this.exchangeCode = "";
          // 刷新用户信息
          this.getCurrentUserInfo();
        } else {
          uni.showToast({
            title: res.msg || "兑换失败",
            icon: "none",
          });
        }
      } catch (err) {
        console.error("兑换失败：", err);
        uni.showToast({
          title: err.msg || "兑换失败",

          icon: "none",
        });
      } finally {
        this.isExchanging = false;
      }
    },
  },
};
</script>

<style lang="scss">
.exchange-container {
  min-height: 100vh;
  background: #fff;
  padding: 40rpx 30rpx;
}

.header {
  margin-bottom: 60rpx;

  .title {
    font-size: 44rpx;
    color: #333;
    font-weight: 500;
  }
}

.balance-grid {
  display: flex;
  border: 1px solid #eee;
  margin-bottom: 60rpx;

  .grid-item {
    flex: 1;
    padding: 30rpx;
    text-align: center;

    &:first-child {
      border-right: 1px solid #eee;
    }

    .label {
      font-size: 26rpx;
      color: #999;
      margin-bottom: 16rpx;
      display: block;
    }

    .value {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
      margin-right: 8rpx;
    }

    .unit {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.section-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
  font-weight: bold; /* 添加字体加粗 */
}

.exchange-info {
  margin-bottom: 40rpx;

  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1px solid #eee;

    .label {
      color: #333;
      font-size: 28rpx;
    }

    .value {
      color: #333;
      font-size: 28rpx;
    }

    .input-wrapper {
      flex: 1;
      margin-left: 40rpx;

      input {
        width: 90%;
        height: 88rpx;
        border: 1px solid #eee;
        padding: 0 30rpx;
        font-size: 28rpx;
        text-align: right;
      }
    }
  }
}

.notice-section {
  margin-bottom: 60rpx;

  .notice-content {
    border: 1px solid #eee;
    padding: 30rpx;

    .notice-item {
      font-size: 26rpx;
      color: #666;
      line-height: 1.6;
      display: block;

      &:not(:last-child) {
        margin-bottom: 16rpx;
      }
    }
  }
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background: #fff;
  color: #333;
  font-size: 32rpx;
  border: 1px solid #333;
  transition: all 0.3s;

  &:active {
    background: #333;
    color: #fff;
  }

  &[disabled] {
    background: #fafafa;
    border-color: #eee;
    color: #999;
  }
}
</style>
